﻿using BarrageGrab;
using BarrageGrab.Entity.Enums;
using BarrageGrab.Entity.Models;
using BarrageGrab.Entity.Models.Douyin;
using BarrageGrab.Entity.Protobuf.Douyin;
using NAudio.Wave;
using Newtonsoft.Json;
using SQLitePCL;
using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Media;
using System.Reflection;
using System.Speech.Synthesis;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Vlc.DotNet.Forms;
using YOUYOU.Core;
using MethodInvoker = System.Windows.Forms.MethodInvoker;

namespace 抖音弹幕
{
    public partial class MainWindow : Form
    {
        #region 属性&字段

        /// <summary>
        /// 打印的行数
        /// </summary>
        static int printCount = 0;

        #endregion
        private List<BarrageGrab.Entity.Models.GiftConfig> giftConfig = new List<BarrageGrab.Entity.Models.GiftConfig>();
        private Config config = new Config();
        public MainWindow()
        {

            InitializeComponent();
            list();

            string str = System.AppDomain.CurrentDomain.BaseDirectory;
            webView21.Source = new Uri(str + "snake.html");
        }
        public void list()
        {
            giftConfig = SqlsugarHelper.db.Queryable<BarrageGrab.Entity.Models.GiftConfig>().ToList();
            dataGridView1.DataSource = giftConfig;

            //config = SqlsugarHelper.db.Queryable<Config>().ToList().FirstOrDefault();

        }
        private void MainWindow_Load(object sender, EventArgs e)
        {
            this.Text = $"抖音快手Tiktok视频号WSS弹幕助手({GlobalConfigs.Version})";

            this.lblLocalWebSocket_Location.Text = GlobalConfigs.LocalWebSocketServer_Location;

            #region Platform
            var platformList = new List<KeyValuePair<string, int>>();
            platformList.Add(new KeyValuePair<string, int>("抖音", 1));

            #endregion

        }
        private void btnReBoot_LocalWebSocket_Click(object sender, EventArgs e)
        {
            ApplicationRuntime.LocalWebSocketServer?.ReStart();
        }



        private void btnGrab_Click(object sender, EventArgs e)
        {
            object? tag = this.btnGrab.Tag;

            if (tag == null || "start".Equals(tag.ToString()?.ToLower()))
            {
                string liveUrl = this.txtLiveUrl.Text.Trim();
                if (string.IsNullOrEmpty(liveUrl))
                {
                    MessageBox.Show("LiveId不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                ApplicationRuntime.BarrageGrabService?.Start(liveUrl);


                this.txtLiveUrl.Enabled = false;
                this.btnGrab.Text = "停止";
                this.btnGrab.Tag = "Stop";
            }
            else
            {
                ApplicationRuntime.BarrageGrabService?.Stop();

                this.txtLiveUrl.Enabled = true;
                this.btnGrab.Text = "开始";
                this.btnGrab.Tag = "Start";
            }

        }

        public void PrintConsole(string message, OpenBarrageMessage dom)
        {
            var stringbuff = message.Split(" ");
            if (message.Contains("礼物"))
            {
                string liw = stringbuff[6].ToString().Trim();
                string name = stringbuff[1].ToString().Trim();
                string sex = "大哥";
                if (stringbuff[2].ToString().Trim().Equals("女"))
                {
                    sex = "姐";
                }

                var info = giftConfig.Where(t => t.Gift == liw).ToList().FirstOrDefault();
                if (info == null)
                {
                    playMsg($"感谢我 {name} {sex}送的" + liw + "蛇加速了");
                    //没有配置过的礼物按照 抖币价格执行添加速度
                    var dbdata = SqlsugarHelper.db.Queryable<DouyinMsgGifts>().Where(t => t.GiftName == liw).ToList().FirstOrDefault();
                    if (dbdata != null)
                    {
                        int dyb = dbdata.DiamondCount;
                        for (int i = 0; i < dyb; i++)
                        {
                            this.Invoke((MethodInvoker)delegate
                            {
                                webView21.CoreWebView2.ExecuteScriptAsync("accelerateGame();");
                            });
                        }
                    }

                }
                else
                {
                    string path = info.Path;
                    switch (info.JsFunction)
                    {
                        case "加速":
                            playMsg($"感谢我 {name} {sex}送的" + liw + "蛇加速了");
                            for (int i = 0; i < info.Num.ObjToInt(); i++)
                            {
                                this.Invoke((MethodInvoker)delegate
                                {
                                    webView21.CoreWebView2.ExecuteScriptAsync("accelerateGame();");
                                });
                            }
                            break;
                        case "减速":
                            playMsg($"感谢我 {name} {sex}送的" + liw + "蛇减速了");
                            for (int i = 0; i < info.Num.ObjToInt(); i++)
                            {
                                this.Invoke((MethodInvoker)delegate
                                {
                                    webView21.CoreWebView2.ExecuteScriptAsync("decelerateGame();");
                                });
                            }
                            break;
                        case "画食物":
                            playMsg($"感谢我 {name} {sex}送的" + liw + "食物位置换了");
                            for (int i = 0; i < info.Num.ObjToInt(); i++)
                            {
                                this.Invoke((MethodInvoker)delegate
                                {
                                    webView21.CoreWebView2.ExecuteScriptAsync("drawNewFood();");
                                });
                            }
                            break;
                        case "音频":
                            this.Invoke((MethodInvoker)delegate
                            {
                                AudioPlay(path);
                            });
                            break;
                        case "视频":
                            this.Invoke((MethodInvoker)delegate
                            {
                                vlcPlay(path);
                            });
                            break;
                        default:
                            break;
                    }
                    for (int i = 0; i < info.Num.ObjToInt(); i++)
                    {
                        this.Invoke((MethodInvoker)delegate
                        {
                            webView21.CoreWebView2.ExecuteScriptAsync("accelerateGame();");
                        });
                    }
                }



            }

            if (checkBoxjr.Checked && message.Contains("进入"))
            {
                playMsg("欢迎 " + stringbuff[1].ToString() + "进入直播间");
                Print(message);
            }
            if (checkBoxdm.Checked && message.Contains("弹幕"))
            {
                string dm = stringbuff[4].ToString().Trim();
                if (dm.Equals("666"))
                {
                    playMsg("蛇加速了");
                    this.Invoke((MethodInvoker)delegate
                    {
                        webView21.CoreWebView2.ExecuteScriptAsync("accelerateGame();");
                    });
                }
                else if (dm.Equals("888"))
                {
                    playMsg("蛇减速了");
                    this.Invoke((MethodInvoker)delegate
                    {
                        webView21.CoreWebView2.ExecuteScriptAsync("decelerateGame();");
                    });
                }
                Print(message);
            }
            if (checkBoxdz.Checked && message.Contains("点赞"))
            {
                Print(message);
            }
            if (checkBoxlw.Checked && message.Contains("礼物"))
            {
                Print(message);
            }
            if (checkBoxfx.Checked && message.Contains("分享"))
            {
                Print(message);
            }
            if (checkBoxtj.Checked && message.Contains("统计"))
            {
                Print(message);
            }
            if (checkBoxjr.Checked && message.Contains("进入"))
            {
                Print(message);
            }


        }

        public void Print(string message)
        {
            this.Invoke(new Action(() =>
            {
                this.txtConsole.AppendText(message + "\r\n");
                this.txtConsole.ScrollToCaret();

                if (++printCount > 10000)
                {
                    printCount = 0;
                    this.txtConsole.Clear();
                }
            }));
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            GiftConfig giftConfig = new GiftConfig();
            giftConfig.ShowDialog();
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            list();
        }

        private void playMsg(string msg)
        {
            Task.Run(() =>
            {
                var speaker = new SpeechSynthesizer();
                speaker.Volume = 100;
                speaker.Rate = 1;
                speaker.Speak(msg);
            });
        }

        private void AudioPlay(string name)
        {
            string str = System.AppDomain.CurrentDomain.BaseDirectory;

            if (name!="")
            {
                using (var audioFile = new AudioFileReader(str + $"Media\\Audio\\{name}"))
                using (var outputDevice = new WaveOutEvent())
                {
                    outputDevice.Init(audioFile);
                    outputDevice.Play(); // 异步执行

                    while (outputDevice.PlaybackState == PlaybackState.Playing)
                    {
                        Thread.Sleep(1000);
                    }
                }
            }
            else
            {
                string[] files = Directory.GetFiles(@str + "Media\\Audio\\", "*");
                int video = config.Video;
                Random random = new Random();
                int randomNumber = random.Next(1, files.Length);
                string path = files[randomNumber].ToString();
                using (var audioFile = new AudioFileReader(path))
                using (var outputDevice = new WaveOutEvent())
                {
                    outputDevice.Init(audioFile);
                    outputDevice.Play(); // 异步执行

                    while (outputDevice.PlaybackState == PlaybackState.Playing)
                    {
                        Thread.Sleep(1000);
                    }
                }
            }
            


        }
        public void vlcPlay(string path)
        {
            vlcControl1.Visible = true;
            string str = System.AppDomain.CurrentDomain.BaseDirectory;
            if (path != "")
            {
                vlcControl1.SetMedia(new FileInfo(str + $"Media\\Video\\{path}.mp4"));
            }
            else
            {
                string[] files = Directory.GetFiles(@str+ "Media\\Video\\", "*");
                int video = config.Video;
                Random random = new Random();
                int randomNumber = random.Next(1, files.Length);
                string name = files[randomNumber].ToString();
                vlcControl1.SetMedia(new FileInfo(name));

            }



            vlcControl1.Play();
        }

        private void vlcControl1_VlcLibDirectoryNeeded(object sender, Vlc.DotNet.Forms.VlcLibDirectoryNeededEventArgs e)
        {
            var currentAssembly = Assembly.GetEntryAssembly();
            var currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName;
            string path = Application.StartupPath;
            if (currentDirectory == null)
                return;
            if (IntPtr.Size == 4)
                e.VlcLibDirectory = new DirectoryInfo(Path.GetFullPath(path + "\\libvlc\\win-x86"));
            else
                e.VlcLibDirectory = new DirectoryInfo(Path.GetFullPath(path + "\\libvlc\\win-x64"));

            if (!e.VlcLibDirectory.Exists)
            {
                var folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
                folderBrowserDialog.Description = "Select Vlc libraries folder.";
                folderBrowserDialog.RootFolder = Environment.SpecialFolder.Desktop;
                folderBrowserDialog.ShowNewFolderButton = true;
                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                {
                    e.VlcLibDirectory = new DirectoryInfo(folderBrowserDialog.SelectedPath);
                }
            }
        }

        private void vlcControl1_EndReached(object sender, Vlc.DotNet.Core.VlcMediaPlayerEndReachedEventArgs e)
        {
            // 确保在 UI 线程中修改控件
            if (vlcControl1.InvokeRequired)
            {
                // 如果当前不是 UI 线程，则通过 Invoke 调用此方法
                vlcControl1.Invoke(new Action(() =>
                {
                    vlcControl1.Visible = false;  // 隐藏 VLC 控件
                    //MessageBox.Show("视频播放完毕，播放器已隐藏！");
                }));
            }
            else
            {
                // 如果已经在 UI 线程，直接修改控件
                vlcControl1.Visible = false;  // 隐藏 VLC 控件
                //MessageBox.Show("视频播放完毕，播放器已隐藏！");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            vlcPlay("");
        }
    }
}
